package com.Yourweibo;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import weibo4android.Count;
import weibo4android.Paging;
import weibo4android.Status;
import weibo4android.User;
import weibo4android.Weibo;
import weibo4android.WeiboException;
import weibo4android.http.AccessToken;
import weibo4android.http.RequestToken;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;

import com.Yourweibo.status.StatusInformation;
import com.Yourweibo.status.TimeLineConstant;
import com.Yourweibo.util.HttpLoadAsync;
import com.Yourweibo.util.UserDatabase;
import com.Yourweibo.util.HttpLoadAsync.HttpCallBack;
 

public class YouWeiboActivity extends Activity {
    /** Called when the activity is first created. */
 
	private ProgressBar loadingStatusbar;
	private ProgressDialog progressdialog;
	private List<Count> count;
	private ListView userMessageList;
 	private Spinner UserList;
 	private ImageView LoginButton;
	
	private UserMessageTask sTask;
	private Weibo weibo;
	private UserDatabase Udb;
	private SimpleCursorAdapter UserListAdapter;
	private Context context;
	private String [] fromColumns = new String[] {UserDatabase.FIELD_1,UserDatabase.FIELD_2,UserDatabase.FIELD_3,UserDatabase.FIELD_4};
	private int    [] toLayout=new int[]{R.id.user_list_access_token,R.id.user_list_access_secret,R.id.user_list_user_name,R.id.user_list_id};
	 
	
    @Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		context=YouWeiboActivity.this;
		System.setProperty("weibo4j.oauth.consumerKey", Weibo.CONSUMER_KEY);
		System.setProperty("weibo4j.oauth.consumerSecret",	Weibo.CONSUMER_SECRET);
		setContentView(R.layout.login_layout);

		UserList = (Spinner) this.findViewById(R.id.login_user_list);
	    loadingStatusbar=(ProgressBar)this.findViewById(R.id.login_loadingbar);
		userMessageList=(ListView)this.findViewById(R.id.login_listView1);
		LoginButton=(ImageView)this.findViewById(R.id.login_loginbutton);
		Udb = new UserDatabase(this);
 
		 
		Cursor cursor = Udb.selectALL();
		// 有用户信息
		//从DB取出
		if (cursor.getCount()!=0) {
			//写入下拉菜单
			setDataToDropList(cursor);
			System.out.println("selected items"+UserList.getSelectedItemId());
			//得到 Token
		 	String token=cursor.getString(1);
			String tokenSecret=cursor.getString(2);
			//关闭数据库
			Udb.closeDB();
			
			//实例化 weibo 并设置token
			weibo=new Weibo();
			weibo.setToken(token,tokenSecret);
			
			//讲weibo 加入 Timeline常量中作为全局变量
			TimeLineConstant.getInstance();
			TimeLineConstant.setWeibo(weibo);
			
			//异步加载微博状态信息
			sTask=new UserMessageTask();
		  
			sTask.execute(weibo);
 
		
		} else {
			// 无用户信息，指向授权页面
			Uri uri = this.getIntent().getData();
			if (uri == null) {
				//是否第一次使用
				checkFirstDialog();

			} else {
				//授权后 将用户信息写入db
				OAuthUserToDB(uri);
				cursor=Udb.selectALL();
				//用户信息加入下拉菜单
				setDataToDropList(cursor);
			}

		}
		
		//进入主界面
		LoginButton.setOnTouchListener(new OnTouchListener(){
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				if(event.getAction()==MotionEvent.ACTION_UP){
				Intent intent=new Intent(context,mainActivity.class);
				context.startActivity(intent);
				
			
					
				}
	
				return false;
			}} );
		
		
	}
    
    

	public void setDataToDropList(Cursor cursor){
		UserListAdapter = new SimpleCursorAdapter(this,
				R.layout.user_list_layout, cursor, fromColumns, toLayout);
		UserList.setAdapter(UserListAdapter);
		
	}


	 /*
	  * 
	  * 将用户的token 写入数据库
	  * */
	public void OAuthUserToDB(Uri uri){
		RequestToken requestToken= OAuthConstant.getInstance().getRequestToken();
		AccessToken accessToken;
		try {
			accessToken = requestToken.getAccessToken(uri.getQueryParameter("oauth_verifier"));
			OAuthConstant.getInstance().setAccessToken(accessToken);
			System.out.println(accessToken);

			weibo=OAuthConstant.getInstance().getWeibo();
			weibo.setToken(OAuthConstant.getInstance().getToken(),OAuthConstant.getInstance().getTokenSecret());
 
			//验证登录
			User user=weibo.verifyCredentials();
			
			saveUser(user);
		
		} catch (WeiboException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	 
		
	}
    public void saveUser(User user){
    	
    	if (null != user) {

			// access token ,access secret, username,userid
			Udb.insert(new String[] {
					OAuthConstant.getInstance().getToken(),
					OAuthConstant.getInstance().getTokenSecret(),
					user.getName() }, user.getId());
		}
    	
    }
    
    public void checkFirstDialog(){
    	AlertDialog.Builder oAthverifiedDialog=new AlertDialog.Builder(this);
    	oAthverifiedDialog.setMessage("第一次使用此应用将进行新浪微博的认证，是否继续？")
    	.setPositiveButton("是",new OnClickListener(){

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				Weibo weibo=new Weibo();
				try {
					RequestToken requestToken=weibo.getOAuthRequestToken("youweibo://YouWeiboActivity");
					OAuthConstant.getInstance().setRequestToken(requestToken);
					Uri uri = Uri.parse(requestToken.getAuthenticationURL()+ "&display=mobile");
	    			startActivity(new Intent(Intent.ACTION_VIEW, uri));
				
				
				} catch (WeiboException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				
			}} ).show();
    }
    
    //异步加载数据
    class UserMessageTask extends AsyncTask<Weibo, Integer,  SimpleAdapter > {
   	 
    	 

		@Override
		protected void onPostExecute(SimpleAdapter result) {
			// TODO Auto-generated method stub
  
	  		System.out.println("onPostExecute~~~~~~~~~");
	  		//当exectue 执行结束之后 将 result放入 userMessageList 中
	  		userMessageList.setAdapter(result);
	  		userMessageList.postInvalidate();
			loadingStatusbar.setVisibility(View.GONE);
	 
		}
		 
    	@Override
    	protected void onProgressUpdate(Integer... values) {
    		// TODO Auto-generated method stub
    		super.onProgressUpdate(values);
    	}
    	
 	  
    	@Override
    	protected SimpleAdapter doInBackground(Weibo... params) {
    		// TODO Auto-generated method stub
    		//得到 微博本人状态信息  
    		
    		long[] itemsCount = StatusInformation.getMessagesCount(params[0]);
			if(itemsCount!=null){
				
				return putDataToAdapter(itemsCount);
			}else{
				
				return null;
			}

			
    	}
    	 //unread list
        //0. comments 1.Mentions 2.secret Message,3.followers
     
     	public SimpleAdapter putDataToAdapter(long[] itemsCount){
     		SimpleAdapter pbAdapter = null;
     		//从Strings.xml获得 字符串 数组
     		String [] UserMessage = context.getResources().getStringArray(
 					R.array.message_item_array);
     		
     		//构建 hash表
 			ArrayList<HashMap> UsermessageList = new ArrayList<HashMap>();
 			int messageListSize = UserMessage.length;
 			for (int i = 0; i < messageListSize; i++) {
 				HashMap map = new HashMap();
 				map.put("itemName", UserMessage[i]);
 				map.put("itemInfo", itemsCount[i]);
 				map.put("itemIntent", "");
 				UsermessageList.add(map);
 			}
 			//设置映射
 			String[] itemMap = { "itemName", "itemInfo" };
 			int[] layoutMap = { R.id.user_list_message_itemname,R.id.user_list_access_item_value };
 			pbAdapter = new SimpleAdapter(YouWeiboActivity.this,
 			(List<? extends Map<String, ?>>) UsermessageList, R.layout.user_messge_list, itemMap, layoutMap);
     		 
     		
     		return pbAdapter;
     		
     	}
    }
    	
}